'use strict'

var mongoose = require('mongoose')
var xss = require('xss')

var User = mongoose.model('User')
var uuid = require('uuid')

var sms = require('../service/sms')

exports.test = function*(next) {
	this.body = {
		data: {
			name: 'slm'
		}
	}
	return next
}

exports.signup = function*(next) {
	var phoneNumber = xss(this.request.body.phoneNumber.trim())

	var user = yield User.findOne({
			phoneNumber: phoneNumber
		}).exec()
		// 调用exec 返回一个promise

	var verifyCode = sms.getCode()

	if (!user) {
		var accessToken = uuid.v4()

		user = new User({
			phoneNumber: xss(phoneNumber),
			verifyCode: verifyCode,
			accessToken: accessToken,
			avatar: 'https://s.luosimao.com/images/website/logo.png',
			nickname: '测试'
		})
	} else {
		user.verifyCode = verifyCode
	}

	try {
		user = yield user.save()
	} catch (e) {
		this.body = {
			success: false,
			err: e
		}
		return next
	}

	var msg = '您的注册验证码是' + user.verifyCode

	try {
		// sms.send(user.phoneNumber, msg)
		console.log(user.verifyCode)
	} catch (e) {
		this.body = {
			success: false,
			err: 'sms服务异常'
		}
		return next
	}

	this.body = {
		success: true
	}


}

exports.verify = function*(next) {
	var verifyCode = xss(this.request.body.verifyCode.trim())
	var phoneNumber = xss(this.request.body.phoneNumber.trim())

	if (!verifyCode || !phoneNumber) {
		this.body = {
			success: false,
			err: '验证不通过'
		}
		return next
	}

	var user = yield User.findOne({
		phoneNumber: phoneNumber,
		verifyCode: verifyCode
	}).exec()

	if (user) {
		user.verified = true
		user = yield user.save()
		this.body = {
			success: true,
			data: {
				nickname: user.nickname,
				accessToken: user.accessToken,
				avatar: user.avatar,
				_id: user._id
			}
		}
	} else {
		this.body = {
			success: false,
			err: '验证未通过'
		}
	}
}

exports.update = function*(next) {
	var body = this.request.body
	var user = this.session.user
	var fields = 'avatar,gender,age,nickname,breed'.split(',')

	fields.forEach(function(field) {
		if (body[field]) {
			user[field] = xss(body[field].trim())
		}
	})

	user = yield user.save()

	this.body = {
		success: true,
		data: {
			nickname: user.nickname,
			accessToken: user.accessToken,
			avatar: user.avatar,
			age: user.age,
			breed: user.breed,
			gender: user.gender,
			_id: user._id
		}
	}
}